package fiuba.descuentos;

import java.util.ArrayList;
import java.util.Vector;

import org.json.JSONException;
import org.json.JSONObject;

import Adapters.BenefitAdapter;
import Entities.Benefit;
import Helpers.ContextHelper;
import Listeners.CustomLocationListener;
import Service.Parameter;
import Service.WellKnownKeys;
import Service.WellKnownMethods;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Login extends ActivityBase {
	private ArrayList<Benefit> benefits;
	private GridView listview;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);   
        
        Button button = (Button) findViewById(R.id.btn_login);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                login();
            }
        });
    }
    
    private void login(){
    	EditText username = (EditText) this.findViewById(R.id.et_un);
		String email = username.getText().toString();
		
		EditText password = (EditText) this.findViewById(R.id.et_pw);
		String pass = password.getText().toString();
			
		Vector props = new Vector();
		Parameter loginEmail = new Parameter(WellKnownKeys.EmailKey,email);
		Parameter loginPass = new Parameter(WellKnownKeys.PasswordKey,pass);
		props.add(loginEmail);
		props.add(loginPass);
				
		
		callService(WellKnownMethods.Login, props);
    }           

	@Override
	public void onServiceCompleted(JSONObject obj, String method) {
		if (WellKnownMethods.Login.compareTo(method) == 0){
			onLoginCompleted(obj);
		}
	}

	private void onLoginCompleted(JSONObject obj) {
		boolean resultSuccess;
		hideLoading();
		try {
			resultSuccess = obj.getBoolean("success");
			if (resultSuccess) {
				ContextHelper.setUserId(obj.getInt("userId"));
				Intent intent = new Intent(this, TopBenefit.class);
				startActivity(intent);
			}else{
				showErrorMessage(obj.getString("message"));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}				
	}	
}